package com.ai.imagetext.controller;

import com.ai.imagetext.dto.TextContentDTO;
import com.ai.imagetext.entity.TextContent;
import com.ai.imagetext.service.TextGenerationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/text")
@RequiredArgsConstructor
public class TextGenerationController {
    
    private final TextGenerationService textGenerationService;
    
    /**
     * 为图片生成文案
     */
    @PostMapping("/generate")
    public ResponseEntity<Map<String, Object>> generateText(@RequestBody TextGenerationRequest request) {
        log.info("Text generation request for image: {}, type: {}, style: {}", 
                request.getImageId(), request.getContentType(), request.getStyleType());
        
        try {
            TextContent.ContentType contentType = TextContent.ContentType.valueOf(request.getContentType());
            TextContent.StyleType styleType = TextContent.StyleType.valueOf(request.getStyleType());
            
            TextContent textContent = textGenerationService.generateTextForImage(
                    request.getImageId(), contentType, styleType, request.getCustomPrompt());
            
            TextContentDTO dto = convertToDTO(textContent);
            
            Map<String, Object> response = createSuccessResponse("文案生成任务已启动");
            response.put("data", dto);
            response.put("message", "文案正在生成中，请稍后查看结果");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Text generation failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 批量生成文案
     */
    @PostMapping("/generate/batch")
    public ResponseEntity<Map<String, Object>> batchGenerateText(@RequestBody BatchTextGenerationRequest request) {
        log.info("Batch text generation request for image: {}", request.getImageId());
        
        try {
            List<TextContent.ContentType> contentTypes = request.getContentTypes().stream()
                    .map(TextContent.ContentType::valueOf)
                    .collect(Collectors.toList());
            
            List<TextContent.StyleType> styleTypes = request.getStyleTypes().stream()
                    .map(TextContent.StyleType::valueOf)
                    .collect(Collectors.toList());
            
            // 异步执行批量生成
            textGenerationService.batchGenerateText(request.getImageId(), contentTypes, styleTypes, request.getCustomPrompt());
            
            Map<String, Object> response = createSuccessResponse("批量文案生成任务已启动");
            response.put("imageId", request.getImageId());
            response.put("contentTypes", request.getContentTypes());
            response.put("styleTypes", request.getStyleTypes());
            response.put("message", "文案正在批量生成中，请稍后查看结果");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Batch text generation failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 重新生成文案
     */
    @PostMapping("/regenerate/{textContentId}")
    public ResponseEntity<Map<String, Object>> regenerateText(@PathVariable Long textContentId, 
                                                            @RequestBody(required = false) Map<String, String> request) {
        log.info("Regenerate text request for content: {}", textContentId);
        
        try {
            String customPrompt = request != null ? request.get("customPrompt") : null;
            TextContent textContent = textGenerationService.regenerateText(textContentId, customPrompt);
            
            TextContentDTO dto = convertToDTO(textContent);
            
            Map<String, Object> response = createSuccessResponse("文案重新生成任务已启动");
            response.put("data", dto);
            response.put("message", "文案正在重新生成中，请稍后查看结果");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Text regeneration failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取图片的所有文案
     */
    @GetMapping("/image/{imageId}")
    public ResponseEntity<Map<String, Object>> getTextContentsForImage(@PathVariable Long imageId) {
        log.info("Getting text contents for image: {}", imageId);
        
        try {
            List<TextContent> textContents = textGenerationService.getTextContentsForImage(imageId);
            List<TextContentDTO> dtos = textContents.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
            
            Map<String, Object> response = createSuccessResponse("获取图片文案成功");
            response.put("data", dtos);
            response.put("imageId", imageId);
            response.put("count", dtos.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Get text contents for image failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 根据类型和风格获取文案
     */
    @GetMapping("/filter")
    public ResponseEntity<Map<String, Object>> getTextContentsByTypeAndStyle(
            @RequestParam(required = false) String contentType,
            @RequestParam(required = false) String styleType) {
        
        log.info("Getting text contents by type: {} and style: {}", contentType, styleType);
        
        try {
            TextContent.ContentType ct = contentType != null ? TextContent.ContentType.valueOf(contentType) : null;
            TextContent.StyleType st = styleType != null ? TextContent.StyleType.valueOf(styleType) : null;
            
            List<TextContent> textContents = textGenerationService.getTextContentsByTypeAndStyle(ct, st);
            List<TextContentDTO> dtos = textContents.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
            
            Map<String, Object> response = createSuccessResponse("获取文案列表成功");
            response.put("data", dtos);
            response.put("contentType", contentType);
            response.put("styleType", styleType);
            response.put("count", dtos.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Get text contents by type and style failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 删除文案
     */
    @PostMapping("/delete/{textContentId}")
    public ResponseEntity<Map<String, Object>> deleteTextContent(@PathVariable Long textContentId) {
        log.info("Deleting text content: {}", textContentId);
        
        try {
            textGenerationService.deleteTextContent(textContentId);
            
            Map<String, Object> response = createSuccessResponse("删除文案成功");
            response.put("textContentId", textContentId);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Delete text content failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 删除图片的所有文案
     */
    @PostMapping("/delete/image/{imageId}")
    public ResponseEntity<Map<String, Object>> deleteAllTextContentsForImage(@PathVariable Long imageId) {
        log.info("Deleting all text contents for image: {}", imageId);
        
        try {
            textGenerationService.deleteAllTextContentsForImage(imageId);
            
            Map<String, Object> response = createSuccessResponse("删除图片所有文案成功");
            response.put("imageId", imageId);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Delete all text contents for image failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 重试失败的文案生成
     */
    @PostMapping("/retry-failed")
    public ResponseEntity<Map<String, Object>> retryFailedGenerations() {
        log.info("Retry failed text generations request");
        
        try {
            // 异步执行重试任务
            textGenerationService.retryFailedGenerations();
            
            Map<String, Object> response = createSuccessResponse("重试失败文案生成任务已启动");
            response.put("message", "正在重新生成失败的文案，请稍后查看结果");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Retry failed text generations failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取文案生成统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getTextGenerationStatistics() {
        log.info("Getting text generation statistics");
        
        try {
            TextGenerationService.TextGenerationStatistics stats = textGenerationService.getTextGenerationStatistics();
            
            Map<String, Object> response = createSuccessResponse("获取文案生成统计信息成功");
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Get text generation statistics failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 转换为DTO
     */
    private TextContentDTO convertToDTO(TextContent textContent) {
        TextContentDTO dto = new TextContentDTO();
        dto.setId(textContent.getId());
        dto.setImageId(textContent.getImage().getId());
        dto.setContent(textContent.getContent());
        dto.setContentType(textContent.getContentType());
        dto.setStyleType(textContent.getStyleType());
        dto.setAiGenerationStatus(textContent.getAiGenerationStatus());
        dto.setCreatedAt(textContent.getCreatedAt());
        dto.setUpdatedAt(textContent.getUpdatedAt());
        return dto;
    }
    
    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
    
    /**
     * 文案生成请求
     */
    public static class TextGenerationRequest {
        private Long imageId;
        private String contentType;
        private String styleType;
        private String customPrompt;
        
        // Getters and Setters
        public Long getImageId() { return imageId; }
        public void setImageId(Long imageId) { this.imageId = imageId; }
        
        public String getContentType() { return contentType; }
        public void setContentType(String contentType) { this.contentType = contentType; }
        
        public String getStyleType() { return styleType; }
        public void setStyleType(String styleType) { this.styleType = styleType; }
        
        public String getCustomPrompt() { return customPrompt; }
        public void setCustomPrompt(String customPrompt) { this.customPrompt = customPrompt; }
    }
    
    /**
     * 批量文案生成请求
     */
    public static class BatchTextGenerationRequest {
        private Long imageId;
        private List<String> contentTypes;
        private List<String> styleTypes;
        private String customPrompt;
        
        // Getters and Setters
        public Long getImageId() { return imageId; }
        public void setImageId(Long imageId) { this.imageId = imageId; }
        
        public List<String> getContentTypes() { return contentTypes; }
        public void setContentTypes(List<String> contentTypes) { this.contentTypes = contentTypes; }
        
        public List<String> getStyleTypes() { return styleTypes; }
        public void setStyleTypes(List<String> styleTypes) { this.styleTypes = styleTypes; }
        
        public String getCustomPrompt() { return customPrompt; }
        public void setCustomPrompt(String customPrompt) { this.customPrompt = customPrompt; }
    }
}